package com.ja.openchat.ui.chat.group;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;

import androidx.lifecycle.ViewModelProviders;

import com.google.gson.JsonObject;
import com.ja.openchat.AppViewModelFactory;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.databinding.ActivityGroupManagerBinding;
import com.ja.openchat.viewmodels.GroupChatManagerViewModel;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.group.GroupManagePermissionInfo;
import com.zy.openchat.core.model.group.SuperGroupInfo;
import com.zy.openchat.core.model.message.ChatInfo;

import java.util.Map;

import me.goldze.mvvmhabit.base.BaseActivity;

public class GroupChatManagerActivity extends BaseActivity<ActivityGroupManagerBinding, GroupChatManagerViewModel> implements View.OnClickListener {

    public ChatInfo chatInfo;

    public static void start(Activity activity, ChatInfo chat) {
        Intent intent = new Intent();
        intent.setClass(activity, GroupChatManagerActivity.class);
        intent.putExtra("chat", chat);
        activity.startActivity(intent);
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_group_manager;
    }


    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public GroupChatManagerViewModel initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用LoginViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(GroupChatManagerViewModel.class);
    }

    @Override
    public void initView() {
        super.initView();
        binding.toolbar.tvBarTitle.setText(getString(R.string.group_management));
        if (getIntent() != null) {
            chatInfo = getIntent().getParcelableExtra("chat");
        } else {
            chatInfo = new ChatInfo();
        }
        viewModel.setContext(this, binding);
        binding.toolbar.ivBarBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        requestOtherPermission();
        resetUI();
    }

    public SuperGroupInfo mSuperGroupInfo;

    public void resetUI() {
        binding.openAllSwitch.setOnCheckedChangeListener(null);
        binding.banAllSwitch.setOnCheckedChangeListener(null);
        binding.canInviteSwitch.setOnCheckedChangeListener(null);
        binding.blockMsgSwitch.setOnCheckedChangeListener(null);

        binding.bandSendImgSwitch.setOnCheckedChangeListener(null);
        binding.bandMGCOutSwitch.setOnCheckedChangeListener(null);
        binding.bandMGCOutHintSwitch.setOnCheckedChangeListener(null);
        binding.canInviteSwitch.setOnCheckedChangeListener(null);
        binding.bandQrCodeSwitch.setOnCheckedChangeListener(null);
//        inviteLinkJoinChatSwitch.setOnCheckedChangeListener(null);

        if (chatInfo.permissions != null) {
            binding.banAllSwitch.setChecked(!chatInfo.permissions.can_send_messages);
            binding.bandLinkSwitch.setChecked(chatInfo.permissions.banSendWebLink);
            binding.blockMsgSwitch.setChecked(chatInfo.permissions.banWhisper);
            binding.bandSendImgSwitch.setChecked(!chatInfo.permissions.can_send_media_messages);
            binding.bandQrCodeSwitch.setChecked(chatInfo.permissions.banSendQRcode);
            binding.canInviteSwitch.setChecked(chatInfo.permissions.can_invite_users);
            binding.bandMGCOutSwitch.setChecked(chatInfo.permissions.kickWhoSendKeyword);
            binding.bandMGCOutHintSwitch.setChecked(chatInfo.permissions.showKickMessage);
        }
        if (mSuperGroupInfo != null) {
            binding.openAllSwitch.setChecked(!TextUtils.isEmpty(mSuperGroupInfo.username));
        } else {
            binding.openAllSwitch.setChecked(false);
        }

        binding.banListLayout.setOnClickListener(this);
        binding.minganciLayout.setOnClickListener(this);

        //开关事件
        binding.openAllSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                modifyPublic(isChecked);
            }
        });
        binding.banAllSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                banAllSwitchClick();
            }
        });
        binding.canInviteSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                memberCanInvideSwitchClick();
            }
        });
        binding.blockMsgSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                banPermission();
            }
        });
        binding.bandSendImgSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                banMediaSwitchClick();
            }
        });
        binding.bandLinkSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                banPermission();
            }
        });
        binding.bandQrCodeSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                banPermission();
            }
        });
        binding.bandMGCOutSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                banPermission();
            }
        });
        binding.bandMGCOutHintSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                banPermission();
            }
        });
    }

    private void loadGroupInfo() {
        if (chatInfo != null && chatInfo.isSuperGroup()) {
            TelegramManager.getTelegramManager().getSuperGroupInfo(this, chatInfo.superGroupId(), new TgResultBlock<SuperGroupInfo>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, SuperGroupInfo obj) {
                    mSuperGroupInfo = obj;
                    resetUI();
                }

                @Override
                public void onTimeout(Map<String, Object> request) {

                }
            });
        }
    }

    private void modifyPublic(boolean isPublic) {
        if (chatInfo == null) {
            return;
        }
        showProgress();
        TelegramManager.getTelegramManager().toggleChannelPublic(this, chatInfo.superGroupId(), isPublic, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                loadGroupInfo();
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    private void requestOtherPermission() {
        if (chatInfo == null) {
            return;
        }
        loadGroupInfo();
        TelegramManager.getTelegramManager().updateChatInfoChatPermession(this, chatInfo, new TgResultBlock<GroupManagePermissionInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, GroupManagePermissionInfo obj) {
                resetUI();
            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });
    }

    private void banPermission() {
        if (chatInfo == null) {
            return;
        }
        banPermission(binding.blockMsgSwitch.isChecked(), binding.bandLinkSwitch.isChecked(), binding.bandQrCodeSwitch.isChecked(), chatInfo.permissions.banSendKeyword, binding.bandMGCOutSwitch.isChecked(), binding.bandMGCOutHintSwitch.isChecked());
    }

    private void banPermission(boolean banWhisper, boolean banSendWebLink, boolean banSendQRcode, boolean banSendKeyword, boolean banWhoSendKeyword, boolean showKickMessage) {
        if (chatInfo == null) {
            return;
        }
        showProgress();
        TelegramManager.getTelegramManager().modifyGroupBannedRightEx(this, chatInfo.id, banWhisper, banSendWebLink, banSendQRcode, banSendKeyword, banWhoSendKeyword, showKickMessage, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                requestOtherPermission();
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
                requestOtherPermission();
            }
        });
    }

    private void banAllSwitchClick() {
        if (chatInfo.permissions != null && binding.banAllSwitch.isChecked() != !chatInfo.permissions.can_send_messages) {
            boolean isBan = binding.banAllSwitch.isChecked();
            showProgress();
            TelegramManager.getTelegramManager().banAllToGroup(this, chatInfo.id, isBan, new TgResultBlock<TgResponse>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                    hideProgress();
                    if (!obj.ok) {
                        showErrorTip(getString(R.string.request_error) + obj.errString);
                        resetUI();
                    } else {
                        chatInfo.permissions.can_send_messages = !isBan;
                        resetUI();
                    }
                }

                @Override
                public void onTimeout(Map<String, Object> request) {
                    hideProgress();
                    showErrorTip(getString(R.string.request_error));
                    resetUI();
                }
            });
        }
    }

    private void banMediaSwitchClick() {
        if (chatInfo == null) {
            return;
        }
        showProgress();
        TelegramManager.getTelegramManager().banMediaToGroup(this, chatInfo, binding.bandSendImgSwitch.isChecked(), new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (!obj.ok) {
                    showErrorTip("设置失败，请稍后重试, " + obj.errString);
                    resetUI();
                } else {
                    resetUI();
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
                resetUI();
            }
        });
    }

    private void memberCanInvideSwitchClick() {
        if (chatInfo.permissions != null && binding.canInviteSwitch.isChecked() != chatInfo.permissions.can_invite_users) {
            boolean can = binding.canInviteSwitch.isChecked();
            showProgress();
            TelegramManager.getTelegramManager().canInvideMemberToGroup(this, chatInfo.id, can, new TgResultBlock<TgResponse>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                    hideProgress();
                    if (!obj.ok) {
                        showErrorTip(getString(R.string.request_error) + obj.errString);
                        resetUI();
                    } else {
                        chatInfo.permissions.can_invite_users = can;
                        resetUI();
                    }
                }

                @Override
                public void onTimeout(Map<String, Object> request) {
                    hideProgress();
                    showErrorTip(getString(R.string.request_error));
                    resetUI();
                }
            });
        }
    }

    private void blockAllSwitchClick() {
        if (chatInfo.permissions != null && binding.blockMsgSwitch.isChecked() != chatInfo.permissions.banWhisper) {
            boolean isBlock = binding.blockMsgSwitch.isChecked();
            showProgress();
            TelegramManager.getTelegramManager().blockPrivateChatToGroup(this, chatInfo.id, isBlock, new TgResultBlock<TgResponse>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                    hideProgress();
                    if (!obj.ok) {
                        showErrorTip(getString(R.string.request_error) + obj.errString);
                        resetUI();
                    } else {
                        chatInfo.permissions.can_add_web_page_previews = !isBlock;
                        resetUI();
                    }
                }

                @Override
                public void onTimeout(Map<String, Object> request) {
                    hideProgress();
                    showErrorTip(getString(R.string.request_error));
                    resetUI();
                }
            });
        }
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.banListLayout:
                GroupRestrictedListActivity.start(this, chatInfo);
                break;
            case R.id.minganciLayout:
                ModifyFieldActivity.start_setGroupSensitiveWord(this, chatInfo.id, "");
                break;
        }
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {
        super.onPointerCaptureChanged(hasCapture);
    }
}